<template>
  <el-scrollbar>
    <div class="post-detail-component" v-loading="isLoading">

      <div class="button-group">
        <!-- 返回按钮 -->
        <el-tooltip effect="light" content="返回" placement="right">
          <el-button type="text" class="back-button" @click="goBack">
            <el-icon>
              <Back />
            </el-icon>
          </el-button>
        </el-tooltip>

        <el-dropdown>
          <el-icon style="font-size: 18px;">
            <More />
          </el-icon>

          <template #dropdown>
            <el-dropdown-menu>

              <el-dropdown-item style="font-size: 18px; padding: 10px" @click="editPost(postDetail.postId)" v-if="showEdit">
                <el-tooltip effect="light" content="编辑" placement="left">
                  <el-icon>
                    <Edit />
                  </el-icon>
                </el-tooltip>
              </el-dropdown-item>

              <el-dropdown-item style="font-size: 18px; padding: 10px" @click="openDelete">
                <el-tooltip effect="light" content="删除" placement="left">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-tooltip>
              </el-dropdown-item>
            </el-dropdown-menu>

          </template>
        </el-dropdown>
      </div>

      <div v-if="postDetail">

        <!-- 动态标题上方显示用户头像、用户名和发布时间 -->
        <el-divider />
        <div class="post-header">
          <el-image :src="postDetail.avatarUrl" class="user-avatar" />

          <div class="user-info">
            <el-row class="post-username">{{ postDetail.name }}</el-row>
            <el-row class="post-meta">{{ postDetail.publishTime }}</el-row>
          </div>

        </div>

        <el-divider />

        <h2 class="post-title">{{ postDetail.title }}</h2>

        <p class="post-content">{{ postContentParsed.content }}</p>

        <div>
          <el-image v-for="(url, idx) in postContentParsed.fileUrlList" :src="url" :key="idx" class="post-image" />
        </div>

        <el-divider />

        <!-- 发布评论 -->
        <el-tooltip effect="light" content="发布评论" placement="top">
          <div class="action-buttons">
            <el-button type="text" class="comment-button" @click="toggleComment">
              评论
            </el-button>
          </div>
        </el-tooltip>
        <div v-if="showCommentInput">
          <el-input type="textarea" class="comment-input" :rows="4" placeholder="请输入评论内容" v-model="commentInput"
            clearable :autosize="{ minRows: 3 }"></el-input>

          <div class="comment-button-group">
            <el-button type="info" @click="showCommentInput = false" round>
              关闭
            </el-button>
            <el-button type="primary" @click="submitComment(postDetail.postId, commentInput)" round>
              发布
            </el-button>
          </div>
        </div>

        <!-- 对评论部分进行修改，添加头像、用户名和发布时间显示 -->
        <el-card v-for="comment in commentList" :key="comment.commentId" class="comment-card">
          <div class="comment-header">

            <el-image :src="comment.avatarUrl" class="user-avatar" />

            <div class="user-info">
              <el-row>{{ comment.name }}</el-row>

              <el-row class="post-meta">{{ comment.commentTime }}</el-row>

              <el-button type="text" class="back-button" @click="openDeleteComment(comment.commentId)">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>

            </div>
          </div>

          <p class="post-content">{{ comment.commentContent }}</p>

          <!-- <el-button type="text" class="reply-comment-button" @click="toggleReplyComment(comment.commentId)">
            回复
          </el-button> -->
          <!-- <div v-if="showReplyCommentInput === comment.commentId">
            <el-input type="textarea" :rows="2" placeholder="请输入回复内容" v-model="replyCommentInput"></el-input>
            <el-button type="primary"
              @click="submitReplyComment(postDetail.postId, replyCommentInput, comment.commentId)">
              提交回复
            </el-button>
          </div> -->

        </el-card>
      </div>
    </div>
  </el-scrollbar>
</template>

<script>
import { Image, Button, Input, Card, ElMessage } from 'element-plus';
import { ArrowLeft, Back, More, Edit, Delete } from '@element-plus/icons-vue';
import axios from 'axios';
import { ElMessageBox } from 'element-plus';

export default {
  name: 'PostDetailComponent',
  components: {
    ElImage: Image,
    ElButton: Button,
    ElInput: Input,
    ElCard: Card,
    ArrowLeft,
    Back,
    More,
    Edit,
    Delete
  },
  props: {
    postId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      postDetail: null,
      commentList: [],
      postContentParsed: {},
      showCommentInput: false,
      commentInput: '',
      showReplyCommentInput: null,
      replyCommentInput: '',
      showEdit:false,
      isLoading: true
    };
  },
  created() {
    this.fetchPostDetail();
  },
  methods: {
    goBack() {
      this.$emit('go-back');
    },
    async fetchPostDetail() {
      try {
        const response = await axios.get('/comment/postAndCommentInfo', {
          params: { postId: this.postId },
        });

        if (response.data.code === 0) {
          console.log(response)
          console.log(response.data.data.post)
          this.postDetail = response.data.data.post;

          if (this.postDetail?.studentId == sessionStorage.getItem('studentId')) {
            this.showEdit = true;
          } else {
            this.showEdit = false;
          }

          this.commentList = response.data.data.commentList || [];
          this.postContentParsed = JSON.parse(this.postDetail.postContent); // 解析postContent

        } else {
          ElMessage.error(`获取动态详情失败：${response.data.message}`);
        }

        this.isLoading = false;

      } catch (error) {
        console.error('Error fetching post detail:', error);
        if (error && error.response) {
          ElMessage.error(`获取动态详情失败：${error.response.data?.message || error.response.statusText}`);
        } else if (error && error.request) {
          ElMessage.error('获取动态详情失败：未收到服务器响应');
        } else {
          ElMessage.error(`获取动态详情失败：${error.message}`);
        }
      }
    },
    toggleComment() {
      this.showCommentInput = !this.showCommentInput;
    },
    async submitComment(postId, commentContent) {

      if (!commentContent) {
        ElMessage.warning('请输入评论内容');
        return;
      }

      try {
        const payload = { postId, commentContent };
        const response = await axios.post('/comment/createComment', payload);

        if (response.data.code === 0) {

          ElMessage.success('评论提交成功');
          this.commentInput = ''; // 清空输入框
          this.showCommentInput = false; // 关闭输入框

          axios.get('comment/commentList', {
            params: { postId: this.postId },
          }).then(response => {
            this.commentList=response.data.data; // 添加新评论到列表
          })

        } else {
          ElMessage.error(`评论提交失败：${response.data.message}`);
        }
      } catch (error) {
        console.error('Error submitting comment:', error);
        if (error && error.response) {
          ElMessage.error(`评论提交失败：${error.response.data?.message || error.response.statusText}`);
        } else if (error && error.request) {
          ElMessage.error('评论提交失败：未收到服务器响应');
        } else {
          ElMessage.error(`评论提交失败：${error.message}`);
        }
      }
    },

    openDeleteComment(commentId){
      ElMessageBox.confirm(
        '你确认删除这条评论吗?',
        {
          confirmButtonText: 'YES',
          cancelButtonText: 'NO',
          center: true,
          roundButton: true
        }
      )
        .then(() => {
          this.deleteComment(commentId);
        })
        .catch(() => {

        })
    },
    async deleteComment(commentId) {
      try {
        const response = await axios.delete('/comment/deleteComment', {
          params: { commentId },
        });

        if (response.data.code === 0) {
          ElMessage.success('删除评论成功');
          this.commentList = this.commentList.filter(comment => comment.commentId !== commentId); // 移除已删除的评论
        } else {
          ElMessage.error(`${response.data.message}`);
        }
      } catch (error) {
        console.error('Error deleting comment:', error);
        if (error && error.response) {
          ElMessage.error(`删除评论失败：${error.response.data?.message || error.response.statusText}`);
        } else if (error && error.request) {
          ElMessage.error('删除评论失败：未收到服务器响应');
        } else {
          ElMessage.error(`删除评论失败：${error.message}`);
        }
      }
    },

    openDelete(){
      ElMessageBox.confirm(
        '你确认删除动态吗?',
        {
          confirmButtonText: 'YES',
          cancelButtonText: 'NO',
          center: true,
          roundButton: true
        }
      )
        .then(() => {
          this.deletePost(this.postDetail.postId)
        })
        .catch(() => {

        })
    },
    async deletePost(postId) {
      try {
        const response = await axios.delete('/post/deletePost', {
          params: { postId },
        });

        if (response.data.code === 0) {
          ElMessage.success('删除动态成功');
          this.$emit('post-deleted'); // 通知父组件动态已删除
        } else {
          ElMessage.error(`删除动态失败：${response.data.message}`);
        }
      } catch (error) {
        console.error('Error deleting post:', error);
        if (error && error.response) {
          ElMessage.error(`删除动态失败：${error.response.data?.message || error.response.statusText}`);
        } else if (error && error.request) {
          ElMessage.error('删除动态失败：未收到服务器响应');
        } else {
          ElMessage.error(`删除动态失败：${error.message}`);
        }
      }
    },
    async editPost(postId) {
      this.$emit('edit-post', postId);
    },
    toggleReplyComment(commentId) {
      if (this.showReplyCommentInput === commentId) {
        this.showReplyCommentInput = null;
      } else {
        this.showReplyCommentInput = commentId;
        this.replyCommentInput = '';
      }
    },
    async submitReplyComment(postId, commentContent, replyedCommentId) {
      try {
        const payload = { postId, commentContent, replyedCommentId };
        const response = await axios.post('/comment/createComment', payload);

        if (response.data.code === 0) {
          ElMessage.success('回复提交成功');
          this.replyCommentInput = ''; // 清空输入框
          this.showReplyCommentInput = null; // 关闭输入框
          this.commentList.push(response.data.data); // 添加新回复到列表
        } else {
          ElMessage.error(`回复提交失败：${response.data.message}`);
        }
      } catch (error) {
        console.error('Error submitting reply comment:', error);
        if (error && error.response) {
          ElMessage.error(`回复提交失败：${error.response.data?.message || error.response.statusText}`);
        } else if (error && error.request) {
          ElMessage.error('回复提交失败：未收到服务器响应');
        } else {
          ElMessage.error(`回复提交失败：${error.message}`);
        }
      }
    },
  },
};
</script>

<style scoped>

.post-detail-component{
  margin: 0 15px;
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-avatar {
  width: 50px;
  height: auto;
  border-radius: 50%;
  margin-right: 20px;
}

.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.comment-header .user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 80%;
  margin-right: 20px;
}

.comment-header .user-info {
  margin-right: 10px;
}

.post-title {
  font-size: 24px;
  margin-bottom: 10px;
}

.post-content {
  margin-bottom: 10px;
  text-align: left;
  white-space: pre-wrap;
}

.post-image {
  max-width: 30%;
  margin: 10px;
}

.action-buttons {
  justify-content: center;
}

.post-meta {
  font-size: 12px;
  color: #999;
}

.post-username {
  text-align: left;
  font-size: 18px;
  vertical-align: bottom;
}

.comment-card {
  margin-bottom: 15px;
}

.comment-meta {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
}


.delete-comment-button,
.delete-post-button,
.edit-post-button,
.comment-button,
.reply-comment-button {
  margin: 10px 0;
}

.comment-button-group{
  margin: 10px;
}

.edit-post-button{
  margin: 10px;
}

.comment-input{
  width: 80%;
}

.button-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  /* border: 1px solid black; */
  /* padding: 0 10px; */
}

.back-button {

  padding: 10px;
  border: none;
  font-size: 18px
}

.back-button:hover {
  background-color: #ccc;
}

.post-meta {
  font-size: 14px;
  color: #888;
  text-align: center;
}
</style>
